<?php

namespace App\Http\Controllers\Api\Home;

use App\Http\Controllers\Api\Controller;
use App\Http\Requests\Api\UseraddressRequest;
use App\Http\Requests\Api\UserRequest;
use App\Models\UserAddress;
use App\Transformers\GoodsinfoTransformer;
use App\Transformers\GoodslistTransformer;
use App\Transformers\UsersAddtrssTransformer;
use App\Transformers\UsersTransformer;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;

    class UsersController extends Controller
{
    //

    public function store(UserRequest $request){
        $verifdata = Cache::get($request->verif_key);

        if (!$verifdata){
            return $this->response->error('验证码失效',422);
        }
        if (!hash_equals($verifdata['code'],$request->verif_code)){

            return $this->response->errorUnauthorized('验证码错误');
        }

        $user = User::create([
            'name' => $request->name,
            'phone' => $verifdata['phone'],
            'password' => bcrypt($request->password),
        ]);

        //清楚缓存
        Cache::forget($request->verif_key);

        return $this->response->item($user,new UsersTransformer())->setMeta([
            'access_token' => auth::guard('api')->fromUser($user),
            'token_type' => 'Bearer',
            'expires_in' => auth::guard('api')->factory()->getTTL()*60
        ])->setStatusCode('201');

    }

    public function update(UserRequest $request){
        $user = $this->user();

        $attributes = $request->all();

        if ($request->avatar_image_id){
            $image = Image::find($request->avatar_image_id);
            $attributes['avatar'] = $image->path;
        }
        $user->update($attributes);

        return $this->response->item($user,new UsersTransformer(true));
    }

    public function collects(User $user){
        $goods = $user->collects()->paginate(20);
        return $this->response->paginator($goods,new GoodsinfoTransformer());
    }

    //添加收货地址
    public function addressadd(UseraddressRequest $request,UserAddress $address){

       $address->fill($request->all());
       $address->save();

        return $this->response->array(['message'=>'添加成功'])->setStatusCode(201);

    }

    //修改收货地址
    public function addressupdate(UserAddress $address,UseraddressRequest $request){

        $res=$address->update(

           $request->all()
        );

        if ($res){
            return $this->response->array(['修改成功']);
        }else{
            return $this->response->array(['修改失败']);
        }
    }

    //查看收货地址
    public function addresslist(User $user){

        return $this->response->item($user->addres,new UsersAddtrssTransformer());
    }
    //删除收货地址
    public function addressdelete(UserAddress $address){
        $res=$address->delete();

            return $this->response->array(['message'=>'删除成功'])->setStatusCode(204);
    }
}
